package com.dexgdx.game.action.pack;

import java.util.ArrayList;
import java.util.List;

import com.dexgdx.game.action.IAction;


public class ActionPack{

	private List<IAction> actionList;
	private List<IAction> actionsToRemove;
	
	public ActionPack() {
		super();
		this.actionList = new ArrayList<IAction>();
		this.actionsToRemove = new ArrayList<IAction>();
	}
	
	public ActionPack(IAction action) {
		super();
		this.actionList = new ArrayList<IAction>();
		this.actionsToRemove = new ArrayList<IAction>();
		actionList.add(action);
	}

	public void runNextStep2(){
		if(actionList.size() > 0){
			if(!actionList.get(0).isAsync() ||
					(actionList.get(0).isAsync() && actionList.get(0).isPreloadOver())){
				runAction(0);
				int index = 0;
				do{
					if(actionList.size() > index + 1 
							&& actionList.get(index).isAsync()){
						runAction(index + 1);
					}
					else {
						break;
					}
					index++;
				}
				while(index + 1 < actionList.size());
				
				for (IAction action : actionsToRemove) {
					actionList.remove(action);
				}
				actionsToRemove.clear();
			}
		}
	}

	public void runNextStep(){
		int index = -1;
		do{
			index++;
			runAction(index);
		}
		while(actionList.size() > index + 1 
				&& actionList.get(index).isAsync());
		
		clearFinishedActions();
	}

	private void runAction(int index){
		if(!actionList.get(index).hasStarted()){
			actionList.get(index).initialize();
		}
		actionList.get(index).runNextStep();
		if(actionList.get(index).isFinished()){
			actionsToRemove.add(actionList.get(index));
		}
	}
	private void clearFinishedActions(){
		for (IAction action : actionsToRemove) {
			actionList.remove(action);
		}
		actionsToRemove.clear();
	}
	
	public boolean isFinished() {
		return actionList.size() == 0;
	}
	
	public ActionPack addAction(IAction action){
		actionList.add(action);
		return this;
	}

	public List<IAction> getActionList() {
		return actionList;
	}
	
}
